<?php

namespace app\domain\admin;

use app\model\Device as DeviceModel;

class DeviceDomain extends CommonDomain
{
    public function retrieve($page, $pageSize, $search): array
    {
        try {
            $model = app(DeviceModel::class)->search($search);
            $total = $model->count();
            $list = $model->with(['admin'])
                ->page($page, $pageSize)
                ->order('id DESC')
                ->select();

            return [
                'total' => $total,
                'list' => $list
            ];
        } catch (\Exception $e) {
            $this->errMsg = $e->getMessage();
            return [];
        }
    }

    public function create($type, $title, $description, $serialNumber, $longitude, $latitude, $address, $status): bool
    {
        try {
            $result = app(DeviceModel::class)->save([
                'type' => $type,
                'title' => $title,
                'description' => $description,
                'serial_number' => $serialNumber,
                'longitude' => $longitude,
                'latitude' => $latitude,
                'address' => $address,
                'status' => $status,
            ]);
            return (bool)$result;
        } catch (\Exception $e) {
            $this->errMsg = $e->getMessage();
            return false;
        }
    }

    public function update($id, $type, $title, $description, $serialNumber, $longitude, $latitude, $address, $status): bool
    {
        try {
            $info = app(DeviceModel::class)->find($id);
            if (!$info) {
                $this->errMsg = '设备不存在';
                return false;
            }

            $result = $info->save([
                'type' => $type,
                'title' => $title,
                'description' => $description,
                'serial_number' => $serialNumber,
                'longitude' => $longitude,
                'latitude' => $latitude,
                'address' => $address,
                'status' => $status,
            ]);

            return (bool)$result;
        } catch (\Exception $e) {
            $this->errMsg = $e->getMessage();
            return false;
        }
    }

    public function delete($id): bool
    {
        try {
            $info = app(DeviceModel::class)->find($id);
            if (!$info) {
                $this->errMsg = '设备不存在';
                return false;
            }

            $result = $info->delete();
            $info->admin()->detach();
            return (bool)$result;
        } catch (\Exception $e) {
            $this->errMsg = $e->getMessage();
            return false;
        }
    }
}